<?php
require_once __DIR__ . '/vendor/autoload.php';

require_once __DIR__ . '/util/excel.php';
require_once __DIR__ . '/util/functions.php';

use function util\excelParseFile;


define('DIR_ROOT',      dirname(__FILE__) . '/');

const DIR_DATA = DIR_ROOT . 'data/';
const DIR_TPL = DIR_ROOT . 'tpl/';
const DIR_OUT = DIR_ROOT . 'out/';

// 输出格式、输出目录、输出文件名后缀、输出文件转换
const OUTPUTS = [
    ['json', DIR_OUT . 'json/'],
    ['erl', DIR_OUT . 'erlang/src/data/', '_data', [
        'error' => DIR_OUT . 'erlang/include/error.hrl',
    ],
    ],
];

// 文件后缀、忽略的文件(无后缀)数组
const SKIPS = [
    'json' => ['xxx'],
];


$preloadAutoloadFile = DIR_ROOT . 'preload/autoload.php';
if (file_exists($preloadAutoloadFile)) {
    require_once $preloadAutoloadFile;
}


$gDirOut = '';

if (count($argv) == 2) {
    $inputFile = trim($argv[1]);
    main($inputFile);
} elseif (count($argv) == 1) {
    $inputFiles = getXlsxFiles(DIR_DATA);
    foreach ($inputFiles as $inputFile) {
        main(str_replace('.xlsx', '', $inputFile));
    }
} else {
    echo "php main.php xxx  导出 xxx.xlsx 配置表\n";
    echo "php main.php      导出所有配置表\n";
}


function main(string $inputFile): void {
    $filename = DIR_DATA . "${inputFile}.xlsx";
    if (!file_exists($filename)) {
        echo("main.php File [${filename}] Not Found");
        return;
    }

    $data = excelParseFile($filename);

    foreach (OUTPUTS as $output) {
        $ext = $output[0];
        if (isset(SKIPS[$ext]) && in_array($inputFile, SKIPS[$ext])) continue;

        $tplFile = DIR_TPL . "${inputFile}.${ext}.tpl.php";
        if (!file_exists($tplFile)) {
            echo("main.php File [${tplFile}] Not Found\n");
            continue;
        }

        $outDir = $output[1];

        global $gDirOut;
        $gDirOut = $outDir;

        $outFile = isset($output[2]) ? "${outDir}${inputFile}${output[2]}.${ext}" : "${outDir}${inputFile}.${ext}";
        if (isset($output[3][$inputFile])) {
            $outFile = $output[3][$inputFile];
        }

        $content = parseTemplate($tplFile, $data);
        writeFile($outFile, $content);
    }
}


function parseTemplate(string $tplFile, array $xmlData): string {
    ob_start();
    require_once $tplFile;
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}

function getXlsxFiles(string $dir): array {
    if (($handle = opendir($dir)) === false) return [];

    $files = [];
    while (($file = readdir($handle)) !== false) {
        if (strrchr($file, '.') != '.xlsx') continue;
        $files[] = $file;
    }
    closedir($handle);

    return $files;
}

function writeFile(string $filename, string $content, string $mode = 'wb'): void {
    if (empty($content)) return;

    $oldMask = umask(0);

    $fp = @fopen($filename, $mode);
    @fwrite($fp, $content);
    @fclose($fp);

    umask($oldMask);
}
